package edu.boun.g4.coursity.controller;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.util.Set;

import javax.annotation.Resource;
import org.apache.log4j.Logger;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.base.Splitter;

import edu.boun.g4.coursity.domain.Rating;
import edu.boun.g4.coursity.domain.Course;
import edu.boun.g4.coursity.domain.CoursityUser;
import edu.boun.g4.coursity.service.CourseService;
import edu.boun.g4.coursity.service.RatingService;
import edu.boun.g4.coursity.service.UserService;

import edu.boun.g4.coursity.dto.RatingDto;

/**
 * @author mertusta
 * @author sebnemarslan
 *         Handles and retrieves rating request
 */
@Controller
@RequestMapping("/rating")
public class RatingController {

	@Resource(name = "ratingService")
	private RatingService ratingService;
	
	@Resource(name = "userService")
	private UserService userService;

	@Resource(name = "courseService")
	private CourseService courseService;
	
	protected static Logger logger = Logger.getLogger("service");
	
	@RequestMapping(method = RequestMethod.POST, value = "/add")
	public @ResponseBody
	Response addRating(@RequestParam Integer score) {

		Rating rating = new Rating();
		rating.setRatingScore(score);

		Response response = new Response();
		response.setBody(rating);
		response.setStatus(true);

		ratingService.add(rating);

		return response;
	}

	@RequestMapping(method = RequestMethod.POST, value = "/delete")
	public @ResponseBody
	Response deleteRating(@RequestParam Integer id) {

		Response response = new Response();
		response.setBody(null);
		response.setStatus(true);

		ratingService.delete(id);

		return response;
	}

	@RequestMapping(method = RequestMethod.POST, value = "/edit")
	public @ResponseBody
	Response editRating(@RequestParam Integer score) {

		Rating existingRating = new Rating();
		existingRating.setRatingScore(score);

		Response response = new Response();
		response.setBody(null);
		response.setStatus(true);

		ratingService.edit(existingRating);

		return response;
	}

	@RequestMapping(value = "/list")
	public @ResponseBody
	Response list() {

		List<Rating> all = ratingService.getAll();

		Response response = new Response();
		response.setBody(all);
		response.setStatus(true);

		return response;
	}

	
	
	
	
	/*
	@RequestMapping(value = "/listbycoursetest")
	public @ResponseBody
	Response listByCourseTest() {

		List<Rating> all = ratingService.getAllByCourse(1);

		Response response = new Response();
		response.setBody(all);
		response.setStatus(true);

		return response;
	}
	
	
	@RequestMapping(value = "/listbyusertest")
	public @ResponseBody
	Response listByUserTest() {

		List<Rating> all = ratingService.getAllByUser(1);

		Response response = new Response();
		response.setBody(all);
		response.setStatus(true);

		return response;
	}
	*/
		
	@RequestMapping(value = "/listAllRatingsTest")
	public @ResponseBody
	Response listAllRatingsTest() {

		List<RatingDto> allratings = new ArrayList<RatingDto>();		

		List<Rating> all = ratingService.getAll();
		for(Iterator<Rating> i = all.iterator(); i.hasNext(); ) {
			Rating item = i.next();
			
			CoursityUser cUser = item.getCousityUser();
			int cUserId = 0;
			if (cUser != null)
			{
				cUserId = cUser.getId();
			}
			
			Course c =  item.getCourse();	
			int cId = 0;
			if (c != null)
			{
				cId = c.getCourseId();
			}
			
			allratings.add(new RatingDto(cUserId, cId, item.getRatingScore(),item.getId()));
		}
		
		Response response = new Response();
		response.setBody(allratings);
		response.setStatus(true);

		return response;
	}
	
	
	@RequestMapping(value = "/createRatingTest")
	public @ResponseBody
	Response createRating() {

		
		BufferedReader br = null;
		Splitter delimiterPattern;
		
		try {
 
			String sCurrentLine;
			
			delimiterPattern = Splitter.on(',');
 
			br = new BufferedReader(new FileReader("C:\\temp\\data\\data.txt"));
 						
			while ((sCurrentLine = br.readLine()) != null) {
				Iterator<String> tokens = delimiterPattern.split(sCurrentLine).iterator();
			    String userIDString = tokens.next();
			    String itemIDString = tokens.next();
			    String preferenceValueString = tokens.next();
			    boolean hasTimestamp = tokens.hasNext();
			    String timestampString = hasTimestamp ? tokens.next() : null;
			    
			    Rating newRating = new Rating();
			    newRating.setRatingScore(Integer.valueOf(preferenceValueString).intValue());			    		    
			    int courseId = Integer.valueOf(itemIDString).intValue();
			    int userId = Integer.valueOf(userIDString).intValue();
			    
			    try
			    {
			    	ratingService.add(courseId, userId, newRating);
			    	logger.debug("Added new rating. courseid =" + courseId + ", userid =" + userId);
			    } catch (Exception e) {
					e.printStackTrace();
				}
			    
			}		
			
 
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)br.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
 

		Response response = new Response();
		response.setBody(null);
		response.setStatus(true);

		return response;

	}
	
}